package com.inmotion.android.sdk.moor7;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;
import android.util.Log;


import com.moor.imkf.IMChatManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

import androidx.annotation.NonNull;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;

/**
 * QmLinePlugin
 */
public class QmLinePlugin implements FlutterPlugin, MethodCallHandler {
    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity
    private MethodChannel channel;

    private Context applicationContext;
    private Moo7Helper moo7Helper;


    private BusReceiver busReceiver;

    @Override
    public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
        channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "qm_line");
        channel.setMethodCallHandler(this);

        applicationContext = flutterPluginBinding.getApplicationContext();
        moo7Helper = Moo7Helper.getInstance();
        moo7Helper.setChannel(channel);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.ACTION_RECEIVED_NEW_MSG);
        intentFilter.addAction(IMChatManager.ROBOT_ACTION);
        intentFilter.addAction(IMChatManager.ONLINE_ACTION);
        intentFilter.addAction(IMChatManager.OFFLINE_ACTION);
        intentFilter.addAction(IMChatManager.CLIAM_ACTION);
        intentFilter.addAction(IMChatManager.FINISH_ACTION);
        intentFilter.addAction(IMChatManager.QUEUENUM_ACTION);
        intentFilter.addAction(IMChatManager.USERINFO_ACTION);
        intentFilter.addAction(IMChatManager.INVESTIGATE_ACTION);
        intentFilter.addAction(IMChatManager.LEAVEMSG_ACTION);
        intentFilter.addAction(IMChatManager.WITHDRAW_ACTION);
        intentFilter.addAction(IMChatManager.WRITING_ACTION);

        busReceiver = new BusReceiver(moo7Helper);
        applicationContext.registerReceiver(busReceiver, intentFilter);
    }

    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
        switch (call.method) {
            case Constant.switchServiceRoute:
                moo7Helper.setRequestBaseUrl(call.argument("serviceLine"), result);
                break;
            case Constant.initSDK:
                moo7Helper.initSDK(applicationContext, call.argument("accessId"), call.argument("userName"), call.argument("userId"));
                break;
            case Constant.quitSDK:
                moo7Helper.quitSDK();
                break;
            case Constant.beginChatSession:
                JSONObject params;
                if (call.hasArgument("param")) {
                    Map<String, Map<String, String>> m = call.argument("param");
                    if (m != null && m.containsKey("customField")) {
                        try {
                            params = new JSONObject(m.get("customField"));
                        } catch (Exception e) {
                            e.printStackTrace();
                            params = new JSONObject();
                        }
                    } else params = new JSONObject();
                } else params = new JSONObject();
                moo7Helper.enableChat(call.argument("peerId"), params, result);
                break;
            case Constant.sendTextMessage:
                moo7Helper.sendTextMessage(call.argument("text"), result);
                break;
            case Constant.sendImageMessage:
                moo7Helper.sendImageMessage(call.argument("imagePath"), result);
                break;
            case Constant.sendFileMessage:
                moo7Helper.sendFileMessage(call.argument("filePath"), call.argument("fileName"), call.argument("fileSize"), result);
                break;
            case Constant.resendMessage:
                moo7Helper.resendMessage(call.argument("messageId"), result);
                break;
            case Constant.leaveMessage:
                moo7Helper.leaveMessage(call.argument("peerId"), call.argument("message"), result);
                break;
            case Constant.getMessageList:
                try {
                    Integer page = call.argument("page");
                    moo7Helper.getMessageList(page == null ? 1 : page, result);
                } catch (Exception e) {
                    e.printStackTrace();
                    result.success(FlutterRsp.error("Invalid param [page]").toMap());
                    return;
                }
                break;
            case Constant.deleteLocalMessage:
                moo7Helper.deleteLocalMessage(call.argument("messageId"), result);
                break;
            case Constant.getMessage:
                moo7Helper.getMessage(call.argument("messageId"), result);
                break;
            case Constant.getUnreadMessageCount:
                moo7Helper.getUnreadMessageCount(call.argument("accessId"), call.argument("userName"), call.argument("userId"), result);
                break;
            case Constant.getUnreadMessageList:
                moo7Helper.getUnreadMessageList(call.argument("afterMessageId"), result);
                break;
            default:
                result.error("NOT IMPLEMENTED", "Method [" + call.method + "] is not implemented!", null);
                break;
        }
    }

    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
        channel.setMethodCallHandler(null);
        applicationContext.unregisterReceiver(busReceiver);
    }

    static class BusReceiver extends BroadcastReceiver {

        Moo7Helper moo7Helper;

        BusReceiver(Moo7Helper moo7Helper) {
            this.moo7Helper = moo7Helper;
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (TextUtils.isEmpty(action)) return;
            Log.d("BusReceiver", "onReceive: action->" + action + ", extra->" + (intent.getExtras() == null ? "null" : intent.getExtras().toString()));
            switch (action) {
                case Constant.ACTION_RECEIVED_NEW_MSG:
                    moo7Helper.notifyNewMessage();
                    break;
                case IMChatManager.ONLINE_ACTION:
                    moo7Helper.notifyServiceOnline();
                    break;
                case IMChatManager.OFFLINE_ACTION:
                    moo7Helper.notifyServiceOffline();
                    break;
                case IMChatManager.ROBOT_ACTION:
                    moo7Helper.notifyRobotMessage();
                    break;
                case IMChatManager.CLIAM_ACTION:
                    moo7Helper.notifyChatTaken();
                    break;
                case IMChatManager.QUEUENUM_ACTION:
                    String queueNum = intent.getStringExtra("action_queuenum");
                    moo7Helper.notifyQueueUpdated(TextUtils.isDigitsOnly(queueNum) ? Integer.parseInt(queueNum) : -1);
                    break;
                case IMChatManager.USERINFO_ACTION:
                    String type = intent.getStringExtra("type");
                    String exten = intent.getStringExtra("exten");
                    String username = intent.getStringExtra("username");
                    String avatar = intent.getStringExtra("usericon");
                    moo7Helper.notifyServiceInfoUpdate(type, exten, username, avatar);
                    break;
                case IMChatManager.INVESTIGATE_ACTION:
                    moo7Helper.notifyServiceEvaluation();
                    break;
                case IMChatManager.LEAVEMSG_ACTION:
                    String id = intent.getStringExtra("_id");
                    String peerId = intent.getStringExtra("topeer");
                    moo7Helper.notifyLeaveMsg(id, peerId);
                    break;
                case IMChatManager.WITHDRAW_ACTION:
                    moo7Helper.notifyServiceRecallMsg();
                    break;
                case IMChatManager.WRITING_ACTION:
                    moo7Helper.notifyServiceInputting();
                    break;
            }
        }
    }
}